package com.game.ThauanLopes;

import java.util.HashSet;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.View;

public class Game extends View implements Runnable {

	
	public boolean running = true;
	
	// Thread Interval
	public int interval = 20;
	
	// To catch all the scene game objects and run their Update and Draw methods.
	private HashSet<GameObject> gameObject = new HashSet<GameObject>();
	private Player player;
	
	
	public static Resources resources;
	
	private int canvasHeight;
	private int canvasWidth;

	private Context myContext;
	private Bitmap background;
	
	public static int floor;
	
	public static long deltaTime;
	public long lastTimeCount;
	
	public Game(Context context) 
	{
		super(context);
		
		myContext = context;
		
		this.resources = context.getResources();
		
		background = BitmapFactory.decodeResource(resources,R.drawable.background_game);

		Thread gameThread = new Thread(this);
		gameThread.start();
		
	}
	
	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh)
	{
		this.canvasWidth = w;
		this.canvasHeight = h;
		player = new Player(w,h,gameObject);
		Background bg = new Background(background,new Rect(0,0,w,h),gameObject);
		
	}
	
	public boolean onTouchEvent(MotionEvent event) 
	{
		switch (event.getAction()) 
		{
			case MotionEvent.ACTION_DOWN:
			player.Turn();
		}
		
		return super.onTouchEvent(event);
	}
	
	// Start
	public void Start()
	{

	}
	
	// Update
	public void Update()
	{
		this.deltaTime = (System.currentTimeMillis() - this.lastTimeCount)/1000;
		this.lastTimeCount = System.currentTimeMillis();
		
		if(!gameObject.isEmpty())
		{
			for(GameObject gb : gameObject)
			{
				gb.Update();
			}
		}
	}
	
	//Draw
	@Override
	public void draw(Canvas canvas) 
	{
		
		super.draw(canvas);
		
		
		if(!gameObject.isEmpty())
		{
			for(GameObject gb : gameObject)
			{
				gb.Draw(canvas);
			}
		}
	}

	@Override
	public void run() {
		this.Start();
		
		while(running)
		{
			try
			{
				Thread.sleep(interval);
			}catch(InterruptedException e)
			{
				running = false;
			}
			
			this.Update();
			
			postInvalidate();
		}

	}
}
